﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using GPSTrackingWebsiteManager.ClassManager;

namespace GPSTrackingWebsiteManager.Manager.Pages
{
    public partial class WebDesktop : ClassManager.SessionManagerPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

                SessionManager objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];                
                if (objSessionManager != null)
                {
 
                    if (objSessionManager.IsMaster)
                    {
                        lblUsername.InnerText = objSessionManager.MasterUsername;

                        System.Data.DataTable dtMenu = GPSTrackingDBV2Custom.Data.DataRepository.MenuProvider.GetMenuByMasterUsername(objSessionManager.MasterUsername, 1);

                        Build_Menu(dtMenu);
                                                
                        GetAllCompaniesByMasterUsername(HttpContext.Current.User.Identity.Name);
                    }
                    else
                    {
                        if (objSessionManager.IsAdmin)
                        {
                            lblUsername.InnerText = objSessionManager.AdminUsername;

                            System.Data.DataTable dtMenu = GPSTrackingDBV2Custom.Data.DataRepository.MenuProvider.GetMenuByAdminUsername(objSessionManager.AdminUsername, objSessionManager.CompanyIDSelectedComboBox, 1);

                            Build_Menu(dtMenu);

                            GetAllCompaniesByAdminUsername(HttpContext.Current.User.Identity.Name);
                        }
                    }

                }
                else
                {

                    System.Web.Security.FormsAuthentication.SignOut();
                    Session.Abandon();

                    if (Request.Cookies["GUID"] != null)
                        Response.Redirect("../../" + Request.Cookies["Login"].Value + ".aspx?Guid=" + Request.Cookies["GUID"].Value, true);
                    else
                        Response.Redirect("../../" + Request.Cookies["Login"].Value + ".aspx", true);

                }

                if (CompanyCombo.Items.Count > 1)
                    CompanyCombo.Visible = true;
                else
                    CompanyCombo.Visible = false;
            }            
            
        }

        private void Build_Menu(System.Data.DataTable dataTable)
        {
            IEnumerable<DataRow> menuRows = from p in dataTable.AsEnumerable() select p;

            IEnumerable<DataRow> menuParents = menuRows.Where(x => x.Field<int?>("Parent") == null).OrderBy(x => x.Field<short>("BySequence"));

            foreach (DataRow row in menuParents)
            {
                Telerik.Web.UI.RadMenuItem menuItem = new Telerik.Web.UI.RadMenuItem();
                menuItem.ImageUrl = "../../Template/Icons/16px/" + row.Field<string>("ImageUrl");
                menuItem.Value = row.Field<string>("DirectoryPath") + row.Field<string>("Page");
                if (row.Field<int>("TypeModuleID") == 4) menuItem.NavigateUrl = row.Field<string>("DirectoryPath") + row.Field<string>("Page");
                menuItem.Text = row.Field<string>("Name");
                menuItem.ToolTip = row.Field<string>("ToolTip");
                menuItem.Attributes.Add("Width", Convert.ToString(row.Field<short?>("Width")));
                menuItem.Attributes.Add("Height", Convert.ToString(row.Field<short?>("Heigth")));
                menuItem.Attributes.Add("PosX", Convert.ToString(row.Field<short?>("PositionX")));
                menuItem.Attributes.Add("PosY", Convert.ToString(row.Field<short?>("PositionY")));
                menuItem.Attributes.Add("Page", Convert.ToString(row.Field<string>("Page")));

                IEnumerable<DataRow> menuChilds = menuRows.Where(x => x.Field<int?>("Parent") == row.Field<int>("MenuID")).OrderBy(x => x.Field<short>("BySequence"));

                foreach (DataRow rowChild in menuChilds)
                {
                    Telerik.Web.UI.RadMenuItem menuItemChild = new Telerik.Web.UI.RadMenuItem();
                    menuItemChild.ImageUrl = "../../Template/Icons/16px/" + rowChild.Field<string>("ImageUrl");
                    menuItemChild.Value = rowChild.Field<string>("DirectoryPath") + rowChild.Field<string>("Page");
                    if (rowChild.Field<int>("TypeModuleID") == 4) menuItemChild.NavigateUrl = rowChild.Field<string>("DirectoryPath") + rowChild.Field<string>("Page");
                    menuItemChild.Text = rowChild.Field<string>("Name");
                    menuItemChild.ToolTip = rowChild.Field<string>("ToolTip");
                    menuItemChild.Attributes.Add("Width", Convert.ToString(rowChild.Field<short?>("Width")));
                    menuItemChild.Attributes.Add("Height", Convert.ToString(rowChild.Field<short?>("Heigth")));
                    menuItemChild.Attributes.Add("PosX", Convert.ToString(rowChild.Field<short?>("PositionX")));
                    menuItemChild.Attributes.Add("PosY", Convert.ToString(rowChild.Field<short?>("PositionY")));
                    menuItemChild.Attributes.Add("Page", Convert.ToString(rowChild.Field<string>("Page")));

                    menuItem.Items.Add(menuItemChild);
                }

                rmMenu.Items[0].Items.Add(menuItem);
                rmMenu.Items[0].ImageUrl = "../../Template/Icons/16px/falcon_16x16.png";                
            }

        }

        private void GetAllCompaniesByAdminUsername(string adminUsername)
        {
            SessionManager objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];

            GPSTrackingDBV2.Entities.Administrators AdministratorsEntities = GPSTrackingDBV2.Data.DataRepository.AdministratorsProvider.GetByAdminUsernameCompanyId(adminUsername, objSessionManager.CompanyIDSelectedComboBox);
            GPSTrackingDBV2.Data.DataRepository.AdministratorsProvider.DeepLoad(AdministratorsEntities, true, GPSTrackingDBV2.Data.DeepLoadType.IncludeChildren, typeof(GPSTrackingDBV2.Entities.Companies));

            objSessionManager.CompanyIDSelectedComboBox = AdministratorsEntities.CompanyId;

            int CompanyID = AdministratorsEntities.CompanyId;
            GPSTrackingDBV2.Entities.Companies CompanyEntity = GPSTrackingDBV2.Data.DataRepository.CompaniesProvider.GetByCompanyId(CompanyID);
            objSessionManager.GUID = CompanyEntity.Guid;

            lblCompany.Text = CompanyEntity.Name;
            lblGuid.Text = CompanyEntity.Guid;
            
            HttpContext.Current.Session["SessionManager"] = objSessionManager;

            CompanyCombo.Items.Add(new Telerik.Web.UI.RadComboBoxItem(AdministratorsEntities.CompanyIdSource.Name, AdministratorsEntities.CompanyId.ToString()));

        }

        private void GetAllCompaniesByMasterUsername(string masterUsername)
        {
            GPSTrackingDBV2.Entities.TList<GPSTrackingDBV2.Entities.CompaniesByMasters> CompaniesByMastersEntities = GPSTrackingDBV2.Data.DataRepository.CompaniesByMastersProvider.GetByMasterUsername(masterUsername);
            GPSTrackingDBV2.Data.DataRepository.CompaniesByMastersProvider.DeepLoad(CompaniesByMastersEntities, true, GPSTrackingDBV2.Data.DeepLoadType.IncludeChildren, typeof(GPSTrackingDBV2.Entities.Companies));            
            SessionManager objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];

            foreach (GPSTrackingDBV2.Entities.CompaniesByMasters entity in CompaniesByMastersEntities)
            {                
                CompanyCombo.Items.Add(new Telerik.Web.UI.RadComboBoxItem(entity.CompanyIdSource.Name, entity.CompanyId.ToString()));                
            }

            if (CompaniesByMastersEntities.Count > 0)
            {
                CompanyCombo.SelectedIndex = 0;

                int CompanyID = Convert.ToInt32(CompanyCombo.SelectedValue);
                objSessionManager.CompanyIDSelectedComboBox = CompanyID;               
                GPSTrackingDBV2.Entities.Companies CompanyEntity = GPSTrackingDBV2.Data.DataRepository.CompaniesProvider.GetByCompanyId(CompanyID);
                objSessionManager.GUID = CompanyEntity.Guid;
                Response.Cookies.Add(new HttpCookie("GUID", CompanyEntity.Guid));
                HttpContext.Current.Session["SessionManager"] = objSessionManager;

                CompanyPreviewImage.ImageUrl = "../../Template/Companies/" + CompanyEntity.Logo;
                lblCompany.Text = CompanyEntity.Name;
                lblGuid.Text = CompanyEntity.Guid;


            }
        }

        protected void CompanyCombo_SelectedIndexChanged(object sender, Telerik.Web.UI.RadComboBoxSelectedIndexChangedEventArgs e)
        {
            SessionManager objSessionManager = (SessionManager)HttpContext.Current.Session["SessionManager"];
            
            int CompanyID = Convert.ToInt32(e.Value);

            GPSTrackingDBV2.Entities.Companies CompanyEntity = GPSTrackingDBV2.Data.DataRepository.CompaniesProvider.GetByCompanyId(CompanyID);
            
            objSessionManager.GUID = CompanyEntity.Guid;
            Response.Cookies.Add(new HttpCookie("GUID", CompanyEntity.Guid));        
            objSessionManager.CompanyIDSelectedComboBox = CompanyID;
            HttpContext.Current.Session["SessionManager"] = objSessionManager;

            RadTabStrip1.Tabs.Clear();
            Telerik.Web.UI.RadTab TabHidden = new Telerik.Web.UI.RadTab();
            TabHidden.Style.Add("display","none");
            RadTabStrip1.Tabs.Add(TabHidden);

            CompanyPreviewImage.ImageUrl = "../../Template/Companies/" + CompanyEntity.Logo;
            lblCompany.Text = CompanyEntity.Name;
            lblGuid.Text = CompanyEntity.Guid;
        }

        protected void btnLoginOut_Click(object sender, EventArgs e)
        {
            System.Web.Security.FormsAuthentication.SignOut();
            Session.Abandon();

            if (Request.Cookies["GUID"] != null)
                Response.Redirect("../../" + Request.Cookies["Login"].Value + ".aspx?GUID=" + Request.Cookies["GUID"].Value, true);
            else
                Response.Redirect("../../" + Request.Cookies["Login"].Value + ".aspx", true);
        }       
    }
}